import React, { createContext, ReactElement } from 'react';

import { State, Action, Context } from './types';
import actions from './actions';
import Provider from '../../components/Provider';
import { OrderResultStatus } from './constant';

export const initialState: State = {
  isFetchFailed: false,
  orderInfo: {
    status: OrderResultStatus.Unknown,
    orderId: '',
    payAmount: 0,
    payTime: '',
    productList: []
  }
};

export const reducer = (state: State, action: Action): State => {
  switch (action.type) {
    case 'SET_ORDER_INFO': {
      return { ...state, orderInfo: action.value };
    }
    case 'FETCH_FAILED':
      return { ...state, isFetchFailed: true };
    default:
      return state;
  }
};

export const Store = createContext<Context>({
  state: initialState
});

export default (props: { [key: string]: any }): ReactElement => {
  return (
    <Provider
      reducer={reducer}
      initialState={initialState}
      Store={Store}
      actions={actions}
      {...props}
    />
  );
};
